//
//  YHImageScanTool.m
//  AddressBookCloud
//
//  Created by 000 on 2020/10/13.
//  Copyright © 2020 林宁宁. All rights reserved.
//

#import "YHImageScanTool.h"
#import <SDWebImage/UIImageView+WebCache.h>
#import "YHDefines.h"
#import "YHConstant+Null.h"
#import "UIImage+YHStyle.h"
#import "NSString+YHWebImage.h"
#import "YHSheetView.h"
#import "YHHUD.h"

@interface YHImageScanTool()<UIScrollViewDelegate>

@property (retain, nonatomic) UIVisualEffectView * blurBackground;
@property (retain, nonatomic) UIScrollView * scrollView;
@property (retain, nonatomic) UIImageView * imageViewShow;

@property (retain, nonatomic) UIImage * showImage;
@property (copy, nonatomic) NSString * imageURL;

@end

@implementation YHImageScanTool

-(void)yh_setupUI{
    
    self.tapBgToClose = NO;
    self.backgroundView.backgroundColor = [UIColor clearColor];
    
    [self.contentView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(self);
    }];
    self.contentView.backgroundColor = [UIColor clearColor];
    
    self.blurBackground = [[UIVisualEffectView alloc] initWithEffect:[UIBlurEffect effectWithStyle:UIBlurEffectStyleDark]];
    [self.contentView addSubview:self.blurBackground];
    [self.blurBackground mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(self.contentView);
    }];
      
    
    self.scrollView = [[UIScrollView alloc] initWithFrame:[UIScreen mainScreen].bounds];
    self.scrollView.delegate = self;
    self.scrollView.bouncesZoom = YES;
    self.scrollView.maximumZoomScale = 8.0;
    self.scrollView.minimumZoomScale = 0.3;
    self.scrollView.multipleTouchEnabled = YES;
    self.scrollView.alwaysBounceVertical = NO;
    self.scrollView.showsVerticalScrollIndicator = NO;
    self.scrollView.showsHorizontalScrollIndicator = NO;
    [self.contentView addSubview:self.scrollView];
    
    
    // containerView
    self.imageViewShow =  [[UIImageView alloc] init];
    self.imageViewShow.clipsToBounds = YES;
    self.imageViewShow.userInteractionEnabled = YES;
    [self.scrollView addSubview:self.imageViewShow];

    
    UITapGestureRecognizer * oneTapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(popDismiss)];
    oneTapGesture.numberOfTapsRequired = 1;
    [self.contentView addGestureRecognizer:oneTapGesture];
    
    UILongPressGestureRecognizer * longGesture = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(longPress:)];
    [self.contentView addGestureRecognizer:longGesture];
    
    
    UITapGestureRecognizer *singleClick = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(popDismiss)];
    [self.scrollView addGestureRecognizer:singleClick];
    
    UITapGestureRecognizer *doubleClick = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(doubleClick:)];
    doubleClick.numberOfTapsRequired = 2;
    [self.scrollView addGestureRecognizer:doubleClick];
    
    [singleClick requireGestureRecognizerToFail:doubleClick];
}

-(void)yh_setupData{
    WS(weakSelf)

    if(IsNonNull(self.imageURL)){
        [self.imageViewShow sd_setImageWithURL:[NSURL URLWithString:NullShow(self.imageURL.yh_OSSURLPath)] placeholderImage:[UIImage yh_placeHolder] options:0 completed:^(UIImage * _Nullable image, NSError * _Nullable error, SDImageCacheType cacheType, NSURL * _Nullable imageURL) {
            
            [weakSelf layoutImageView:image];
        }];
    }
    else if(self.showImage && [self.showImage isKindOfClass:[UIImage class]]){
        self.imageViewShow.image = self.showImage;
        [self layoutImageView:self.showImage];
    }
}


- (void)layoutImageView:(UIImage *)image{
    if(!image){
//        [YHHUD showWithText:LS(@"图片加载异常")];
//        [self popDismiss];
        return;
    }
    
    CGFloat contentW = self.bounds.size.width;
    CGFloat contentH = self.bounds.size.height;
    CGRect imageFrame;
    if (image.size.width > contentW || image.size.height > contentH) {
        CGFloat imageRatio = image.size.width/image.size.height;
        CGFloat photoRatio = contentW/contentH;
        
        if (imageRatio > photoRatio) {
            imageFrame.size = CGSizeMake(contentW, contentW/image.size.width*image.size.height);
            imageFrame.origin.x = 0;
            imageFrame.origin.y = (contentH-imageFrame.size.height)/2.0;
        }
        else {
            imageFrame.size = CGSizeMake(contentH/image.size.height*image.size.width, contentH);
            imageFrame.origin.x = (contentW-imageFrame.size.width)/2.0;
            imageFrame.origin.y = 0;
        }
    }
    else {
        imageFrame.size = image.size;
        imageFrame.origin.x = (contentW-image.size.width)/2.0;
        imageFrame.origin.y = (contentH-image.size.height)/2.0;
    }
    self.imageViewShow.frame = imageFrame;
}


- (void)doubleClick:(UITapGestureRecognizer *)gestureRecognizer {

    CGPoint touchPoint = [gestureRecognizer locationInView:self.imageViewShow];
    
    CGFloat newZoomScale = self.scrollView.zoomScale * 1.5;
    if(newZoomScale > self.scrollView.maximumZoomScale){
        newZoomScale = 1;
    }
    
    CGFloat xsize = self.scrollView.frame.size.width/newZoomScale;
    CGFloat ysize = self.scrollView.frame.size.height/newZoomScale;
    [self.scrollView zoomToRect:CGRectMake(touchPoint.x-xsize/2, touchPoint.y-ysize/2, xsize, ysize) animated:YES];
}

- (void)longPress:(UILongPressGestureRecognizer *)gesture{
    if(gesture.state == UIGestureRecognizerStateBegan){
        WS(weakSelf)
        YHSheetView * sheetView = [YHSheetView new];
        [sheetView addHeadTitle:@"选择你的操作"];
        [sheetView addOptionTitle:@"保存到相册" action:^(YHSheetView * _Nonnull alertV) {
            if(!weakSelf.imageViewShow.image){
                YHHUDMsg(@"图片获取失败");
                return;
            }
            
            UIImageWriteToSavedPhotosAlbum(weakSelf.imageViewShow.image,self, @selector(image:didFinishSavingWithError:contextInfo:),nil);
        }];
        [sheetView popShow];
    }
}

- (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo{
    if (error) {
        YHHUDMsg(@"保存失败");
    }
    else {
        YHHUDMsg(@"保存成功");
    }
}

#pragma mark - <UIScrollViewDelegate>

- (UIView *)viewForZoomingInScrollView:(UIScrollView *)scrollView{
    return self.imageViewShow;
}

- (void)scrollViewDidZoom:(UIScrollView *)scrollView{
    CGFloat offsetX = (scrollView.bounds.size.width>scrollView.contentSize.width)?(scrollView.bounds.size.width-scrollView.contentSize.width)*0.5:0.0;
    CGFloat offsetY = (scrollView.bounds.size.height>scrollView.contentSize.height)?(scrollView.bounds.size.height-scrollView.contentSize.height)*0.5:0.0;
    self.imageViewShow.center = CGPointMake(scrollView.contentSize.width*0.5+offsetX, scrollView.contentSize.height*0.5+offsetY);
}



#pragma mark -


+ (void)scanImage:(UIImage *)image imageURL:(NSString *)url{
    YHImageScanTool * scanImageView = [YHImageScanTool new];
    scanImageView.showImage = image;
    scanImageView.imageURL = url;
    [scanImageView popShow];
}

    
@end
